package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.UserRole;
import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.mapper.UserRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class UserRoleService extends BaseService<UserRoleMapper,UserRole> {

	public JSONObject addUsersRole(Users findById, String str) {
		// TODO Auto-generated method stub
		return null;
	}


    /**
     * 查询用户关联的所有角色
     *
     * @param userIds 属性值数组
     * @return 满足条件的所有记录
     */
    public List<UserRole> findByUserId(List<Integer> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<UserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(UserRole::getUserId, userIds);
        return list(queryWrapper);
    }

    /**
     * 查询用户关联的所有角色
     *
     * @param userId 用户ID
     * @return UserRole列表
     */
    public List<UserRole> findByUserId(Integer userId) {
        return findByProperty(UserRole::getUserId, userId);
    }

    /**
     * 查询用户关联的所有角色ID
     * @param userId 用户ID
     * @return roleId 集合
     */
    public Set<Integer> getRoleIdSet(Integer userId) {
        List<UserRole> userRoleList = findByUserId(userId);
        if (userRoleList.isEmpty()) {
            return new HashSet<>();
        }
        return userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
    }

    /**
     * 查询角色关联的用户
     *
     * @param roleId 角色ID
     * @return UserRole列表
     */
    public List<UserRole> findByRoleId(Integer roleId) {
        return findByProperty(UserRole::getRoleId, roleId);
    }

    /**
     * 查询角色关联的所有用户ID
     *
     * @param roleId 角色ID
     * @return userId 集合
     */
    public Set<Integer> getUserIdSet(Integer roleId) {
        List<UserRole> userRoleList = findByRoleId(roleId);
        if (userRoleList.isEmpty()) {
            return new HashSet<>();
        }
        return userRoleList.stream().map(UserRole::getUserId).collect(Collectors.toSet());
    }

    /**
     * 一个角色分配多个用户
     * @param roleId 角色ID
     * @param userIds 分配用户ID集合
     * @return true 表示保存成功
     */
    public boolean save(Integer roleId, Collection<Integer> userIds) {
        if (roleId == null || userIds == null || userIds.isEmpty()) {
            return false;
        }
        // 最终保存数据
        List<UserRole> userRoleListSave = new ArrayList<>();
        // 保存目标
        List<UserRole> userRoleListNew = new ArrayList<>();
        userIds.forEach(userId -> {
            userRoleListNew.add(new UserRole(userId, roleId));
        });
        // 先查找数据库是否存在
        List<UserRole> userRoleListOld = findUserRole(userRoleListNew);
        if (userRoleListOld.isEmpty()) {
            userRoleListSave.addAll(userRoleListNew);
        } else {
            userRoleListSave = userRoleListNew.stream()
                    .filter(userRoleNew -> userRoleListOld.stream()
                            .noneMatch(userRoleOld -> userRoleNew.getUserId().equals(userRoleOld.getUserId())
                                    && userRoleNew.getRoleId().equals(userRoleOld.getRoleId())))
                    .collect(Collectors.toList());
        }
        if (!userRoleListSave.isEmpty()) {
            return insertBatch(userRoleListSave);
        }
        return true;
    }

    /**
     * 角色批量移除用户
     * @param roleId 角色ID
     * @param userIds 移除用户ID集合
     * @return true 表示删除成功
     */
    public boolean delete(Integer roleId, Collection<Integer> userIds) {
        if (roleId == null || userIds == null || userIds.isEmpty()) {
            return false;
        }
        List<UserRole> userRoleListDelete = new ArrayList<>();
        userIds.forEach(userId -> {
            userRoleListDelete.add(new UserRole(userId, roleId));
        });
        // 先查找数据库是否存在
        List<UserRole> userRoleListOld = findUserRole(userRoleListDelete);
        if (!userRoleListOld.isEmpty()) {
            return deleteBatchByIds(userRoleListOld.stream().map(UserRole::getId).collect(Collectors.toList()));
        }
        return true;
    }

    /**
     * 根据用户ID删除
     * @param userId 用户ID
     * @return true 表示删除成功
     */
    public  boolean delete(Integer userId){
        if(userId==null){
            return false;
        }
        LambdaQueryWrapper<UserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserRole::getUserId, userId);
        return remove(queryWrapper);
    }

    /**
     * 新增或更新[用户-角色关系]
     * @param userId 用户ID
     * @param roleIds 该用户分配的角色ID
     * @return true 表示操作成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(Integer userId, Collection<Integer> roleIds) {
        if (userId == null) {
            return false;
        }
        delete(userId);
        if (roleIds != null && roleIds.size() > 0) {
            List<UserRole> userRoleList = new ArrayList<>();
            roleIds.forEach(roleId -> userRoleList.add(new UserRole(userId, roleId)));
            return insertBatch(userRoleList);
        }
        return true;
    }

    /**
     * 根据 userId和roleId组合查找
     * @param userRoleList 查找条件集合
     * @return
     */
    public List<UserRole> findUserRole(Collection<UserRole> userRoleList) {
        if (userRoleList == null || userRoleList.isEmpty()) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<UserRole> queryWrapper = Wrappers.lambdaQuery();
        for (UserRole userRole : userRoleList) {
            Integer userId = userRole.getUserId();
            Integer roleId = userRole.getRoleId();
            queryWrapper.or(userId != null && roleId != null,eqWrapper -> {
                eqWrapper.eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, roleId);
            });
        }
        return list(queryWrapper);
    }




    /**
     * 根据用户id列表删除
     * @param userIdList
     */
    public void remove(List<Integer> userIdList){
        if(userIdList.isEmpty()){
            return;
        }
        LambdaUpdateWrapper<UserRole> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.in(UserRole::getUserId,userIdList);
        remove(lambdaQueryWrapper);
    }

}
